package com.gree.elasticsearch.controller;

import com.gree.elasticsearch.dto.AccountDTO;
import com.gree.elasticsearch.dto.Result;
import com.gree.elasticsearch.security.JwtService;
import com.gree.elasticsearch.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@RequestMapping("/user")
@RestController
public class UserController implements InitializingBean {
    private Logger logger = LoggerFactory.getLogger(UserController.class.getName());

    private AuthenticationManager authenticationManager;

    @Autowired
    private AuthenticationConfiguration authenticationConfiguration;

    @Autowired
    private JwtService jwtService;

    @PostMapping("/authentication")
    public Result authentication(AccountDTO accountDTO) {
        String username = accountDTO.getUsername();
        String password = accountDTO.getPassword();
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password, null);
        Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        DaoAuthenticationProvider daoAuthenticationProvider;
        if (authentication.isAuthenticated()) {
            logger.debug("已经认证");
        }
        Collection<? extends GrantedAuthority> authoritiesList = authentication.getAuthorities();
        authoritiesList.stream().forEach(grantedAuthority -> {
            logger.debug("user finish authentication, username is {}, and it been granted authority is {}", username, grantedAuthority.getAuthority());
        });
        logger.debug("user send login request, and account is authenticated on {}. username is {}, password is {}", System.currentTimeMillis(), accountDTO.getUsername(), accountDTO.getPassword());

        String token = jwtService.createJwt(authentication);

        return ResponseUtil.success(token);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.authenticationManager == null) {
            this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
        }
    }
}
